<?php


namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Admin\Traits\AdminTrait;
use App\Http\Requests\Admin\BaseRequest;
use App\Models\Admin\CustomerMsg;
use App\Models\Admin\CustomerServiceAgent;
use App\Models\Admin\CustomerServiceRole;
use App\Models\Admin\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class CustomerController  extends AdminController
{
    use AdminTrait;

    public function getCustListAll(BaseRequest $request)
    {
        $input = $request->all();
        $rule = [
            'cust_role' => 'required'
        ];
        $validator = Validator::make($input, $rule, $this->vali_msg);
        if ($validator->fails())
            return $this->error(['-1', $validator->errors()->first()]);
        //$list = CustomerServiceAgent::getListAll($input);
        return $this->success([
            //'list' => $list,
            'list' => [],
        ]);
    }

    //获取客服列表
    public function getCustList(BaseRequest $request)
    {
        $input=$request->all();
        $validator = Validator::make($input,$this->vali_rules,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $this->getPageAndSize($input);
        $list=CustomerServiceAgent::getList($input,$this->skip,$this->size);
        $count=CustomerServiceAgent::getCount($input);
        $role_list=CustomerServiceRole::get();
        return $this->success([
            'list'=>$list,
            'count'=>$count,
            'role_list'=>$role_list
        ]);

    }

    //新增客服
    public function addCust(BaseRequest $request)
    {
        $input=$request->only('name','cust_role','head_pic','mobile','email','nickname','account','password','remark','status','service_start_time','service_end_time');
        $rules=[
            'cust_role'=>"required|exists:customer_service_role,id",
//            'head_pic'=>'',
            'name'=>'required',
            'mobile'=>'required|digits:11',
            'email'=>'nullable|email',
            'status'=>'required|in:0,1',
            'account'=>'required|unique:customer_service_agent',
            'nickname'=>'required|unique:customer_service_agent',
            'password'=>'required|alpha_num|digits_between:6,20',
//            'remark'=>'',
        ];

        $validator = Validator::make($input,$rules,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $input['password']=Hash::make($input['password']);
        DB::beginTransaction();
        try {
            $input['company_ids']='';
            $info=CustomerServiceAgent::create($input);
            CustomerServiceAgent::addLog($info->toArray(),[],1);
            DB::commit();
            return $this->success();
        }
        catch (\Exception $exception)
        {
            DB::rollBack();
            return $this->error();
        }
    }

    public function getCustDetail(BaseRequest $request)
    {
        $input=$request->all();
        $rules=[
            'id'=>"required|exists:customer_service_agent,id",
        ];
        $validator = Validator::make($input,$rules,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $id=$input['id'];
        $info=CustomerServiceAgent::getInfo($id);
        return $this->success($info);
    }

    //编辑客服
    public function editCust(BaseRequest $request)
    {
        $input=$request->only('id','name','cust_role','head_pic','mobile','email','nickname','account','password','remark','status','service_start_time','service_end_time');
        $rules=[
            'id'=>'required|exists:customer_service_agent,id',
            'cust_role'=>"required|exists:customer_service_role,id",
//            'head_pic'=>'',
            'name'=>'required',
            'mobile'=>'required|digits:11',
            'email'=>'email',
            'status'=>'required|in:0,1',
            'account'=>[
                'required',
                Rule::unique('customer_service_agent','account')->ignore($input['id']),
            ],
            'nickname'=>[
                'required',
                Rule::unique('customer_service_agent','nickname')->ignore($input['id']),
            ],
//            'remark'=>'',
        ];

        $validator = Validator::make($input,$rules,[
            'account.unique'=>'账号已存在',
            'nickname.unique'=>'昵称已存在',
        ]);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $id=$input['id'];
        DB::beginTransaction();
        try {
            $info=CustomerServiceAgent::find($id);
            $perInfo = $info->getOriginal();//获取修改之前的字段
            $info->cust_role=$input['cust_role'];
            $info->name=$input['name'];
            if(!empty($input['head_pic'])) $info->head_pic=$input['head_pic'];
            if(!empty($input['email'])) $info->email=$input['email'];
            if(!empty($input['remark'])) $info->remark=$input['remark'];
            if(!empty($input['password'])) $info->password=Hash::make($input['password']);;
            $info->mobile=$input['mobile'];
            $info->status=$input['status'];
            $info->account=$input['account'];
            $info->nickname=$input['nickname'];
            $info->service_start_time=$input['service_start_time'];
            $info->service_end_time=$input['service_end_time'];
            $info->save();
            $nextInfo = $info->getChanges();//获取修改之后的字段
            CustomerServiceAgent::addLog($perInfo,$nextInfo,2);
            DB::commit();
            return $this->success();
        }
        catch (\Exception $exception)
        {
            DB::rollBack();
            return $this->error();
        }
    }

    //根据客服id，获取客户列表
    public function getUserListByCustId(BaseRequest $request)
    {
        $input=$request->all();
        $rule=[
          'id'=>'required|exists:customer_service_agent,id'
        ];
        $validator = Validator::make($input,$rule,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $id=$input['id'];
        $company_ids=CustomerServiceAgent::where('id',$id)->value('company_ids');
        $list=[];
        if($company_ids)
        {
            $company_ids_arr=explode(',',$company_ids);
            $where['company_ids']=$company_ids_arr;
            $list=User::getListCust($where);
        }
        return $this->success([
            'list'=>$list,
        ]);
    }

    //根据客户id，获取聊天记录
    public function getMsgListByUserId(BaseRequest $request)
    {
        $input=$request->all();
        $this->vali_rules['user_id']='required|exists:users,id';
        $validator = Validator::make($input,$this->vali_rules,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);
        $this->getPageAndSize($input);
        $list=CustomerMsg::getList($input,$this->skip,$this->size);
        $count=CustomerMsg::getCount($input);
        return $this->success([
            'list'=>$list,
            'count'=>$count
        ]);
    }

}
